﻿using Freshbox2._0.BLL;
using Freshbox2._0.MODEL;
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Freshbox2._0.UI.Controllers
{
    public class WordTestController : BaseController<admin>
    {
        //
        // GET: /WordTest/
        public override BLL.BaseBll<admin> bll
        {
            get
            {
                return new AdminBll();
            }

        }

        private _Application wordApp = null;
        private _Document wordDoc = null;
        public _Application Application
        {
            get
            {
                return wordApp;
            }
            set
            {
                wordApp = value;
            }
        }
        public _Document Document
        {
            get
            {
                return wordDoc;
            }
            set
            {
                wordDoc = value;
            }
        }

                //        if( !Directory.Exists( dir + "//file" ) )
                //{
                //    Directory.CreateDirectory( dir + "//file" );  //创建文件所在目录
                //}
                //string name = DateTime.Now.ToLongDateString() + ".doc";
                //object filename = dir + "//file//" + name;  //文件保存路径


        public ActionResult ExportWord()
        {
            CreateNewDocument("C:\\test.doc");
        
            InsertText("shuqian", "这是一个测试文档的内容");
            InsertValue("shuqian","biaoti");
           //InsertTable("table", 4,3,12.50f); 
            InsertTable();
            SaveDocument("C:\\test122.doc");
            return null;
        }
        /// <summary>
        /// 通过模板创建新文档   
        /// </summary>
        /// <param name="filePath"></param>
        public void CreateNewDocument(string filePath)
        {
            try
            {
                killWinWordProcess();
                wordApp = new ApplicationClass();
                wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                wordApp.Visible = false;
                object missing = System.Reflection.Missing.Value;
                object templateName = filePath;
                wordDoc = wordApp.Documents.Open(ref templateName, ref missing,
                    ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message+"失败!");
            }
        }

        /// <summary>
        /// 保存新文件
        /// </summary>
        /// <param name="filePath"></param>
        public void SaveDocument(string filePath)
        {
            object fileName = filePath;
            object format = WdSaveFormat.wdFormatDocument;//保存格式
            object miss = System.Reflection.Missing.Value;
            wordDoc.SaveAs(ref fileName, ref format, ref miss,
                ref miss, ref miss, ref miss, ref miss,
                ref miss, ref miss, ref miss, ref miss,
                ref miss, ref miss, ref miss, ref miss,
                ref miss);
            //关闭wordDoc，wordApp对象
            object SaveChanges = WdSaveOptions.wdSaveChanges;
            object OriginalFormat = WdOriginalFormat.wdOriginalDocumentFormat;
            object RouteDocument = false;
            wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
            wordApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
        }

        /// <summary>
        /// 在书签处插入值
        /// </summary>
        /// <param name="bookmark"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool InsertValue(string bookmark, string value)
        {
            object bkObj = bookmark;
            if (wordApp.ActiveDocument.Bookmarks.Exists(bookmark))
            {
                wordApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
                wordApp.Selection.TypeText(value);
                return true;
            }
            return false;
        }

        public void InsertTable()
        {
            var list = bll.Search().Select(x => new { x.adminId, x.adminPassword, x.adminUsername, x.state }).ToList();



            object myNothing = System.Reflection.Missing.Value;
            Table table1 = Document.Tables.Add(Application.Selection.Range, 8, 5, ref myNothing, ref myNothing);

            Document.Tables[1].Cell(1, 1).Range.Text = "序号";
            Document.Tables[1].Cell(1, 2).Range.Text = "商品编号";
            Document.Tables[1].Cell(1,3).Range.Text = "商品名称";
            Document.Tables[1].Cell(1, 4).Range.Text = "数量";
            //Document.Tables[1].Cell(1, 5).Range.Text = "商品编号";
            //Document.Tables[1].Cell(1, 6).Range.Text = "商品名称"; 


            for (int i = 1; i < 5; i++)//循环行  i
            {
                for (int j =1; j < 5; j++)//循环列 j
                {
                    if (i == 1)
                    {
                        table1.Cell(j + 1, 1).Range.Text = j.ToString(); //这个应该控制序列号 
                    }
                   table1.Cell(i+1 , j +1).Range.Text = i+1 + "行 " + j +1+ "列";
                }
            }


            //Document.Tables[1].Cell(1, 3).Range.Text = "手机";
            //Document.Tables[1].Cell(2, 1).Range.Text = "重量(kg)";
            //Document.Tables[1].Cell(3, 1).Range.Text = "价格(元)"; 
            //Document.Tables[1].Cell(4, 1).Range.Text = "共同信息";
            //Document.Tables[1].Cell(4, 2).Range.Text = "信息A";
            //Document.Tables[1].Cell(4, 3).Range.Text = "信息B";
            table1.Select();
            table1.Rows.Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowCenter;//整个表格居中

        }
        /// <summary>
        /// 插入表格,bookmark书签  
        ///         //
        //   NumRows:
        //     Required Integer. The number of rows you want to include in the table.
        //
        //   NumColumns:
        //     Required Integer. The number of columns you want to include in the table.
        /// </summary>
        /// <param name="bookmark"></param>
        /// <param name="rows"></param>
        /// <param name="columns"></param>
        /// <param name="width"></param>
        /// <returns></returns>
        public Table InsertTable(string bookmark, int rows, int columns, float width)
        {
            object miss = System.Reflection.Missing.Value;   //
            object oStart = bookmark;
            Range range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置
            Table newTable = wordDoc.Tables.Add(range, rows, columns, ref miss, ref miss);
            //设置表的格式
            newTable.Borders.Enable = 1;  //允许有边框，默认没有边框(为0时报错，1为实线边框，2、3为虚线边框，以后的数字没试过)
            newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;//边框宽度
            if (width != 0)
            {
                newTable.PreferredWidth = width;//表格宽度
            }
            newTable.AllowPageBreaks = false;
            return newTable;
        }
        /// <summary>
        /// 合并单元格 表id,开始行号,开始列号,结束行号,结束列号
        /// </summary>
        /// <param name="n"></param>
        /// <param name="row1"></param>
        /// <param name="column1"></param>
        /// <param name="row2"></param>
        /// <param name="column2"></param>
        public void MergeCell(int n, int row1, int column1, int row2, int column2)
        {
            wordDoc.Content.Tables[n].Cell(row1, column1).Merge(wordDoc.Content.Tables[n].Cell(row2, column2));
        }

        /// <summary>
        /// 合并单元格 表名,开始行号,开始列号,结束行号,结束列号
        /// </summary>
        /// <param name="table"></param>
        /// <param name="row1"></param>
        /// <param name="column1"></param>
        /// <param name="row2"></param>
        /// <param name="column2"></param>
        public void MergeCell(Microsoft.Office.Interop.Word.Table table, int row1, int column1, int row2, int column2)
        {
            table.Cell(row1, column1).Merge(table.Cell(row2, column2));
        }

        /// <summary>
        /// 插入一段文字,text为文字内容   
        /// </summary>
        /// <param name="bookmark"></param>
        /// <param name="text"></param>
        public void InsertText(string bookmark, string text)
        {
            object oStart = bookmark;
            object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;
            Paragraph wp = wordDoc.Content.Paragraphs.Add(ref range);
            wp.Format.SpaceBefore = 6;
            wp.Range.Text = text;
            wp.Format.SpaceAfter = 24;
            wp.Range.InsertParagraphAfter();
            wordDoc.Paragraphs.Last.Range.Text = "\n";
        }

        /// <summary>
        /// 杀掉winword.exe进程
        /// </summary>
        public void killWinWordProcess()
        {
            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("WINWORD");
            foreach (System.Diagnostics.Process process in processes)
            {
                bool b = process.MainWindowTitle == "";
                if (process.MainWindowTitle == "")
                {
                    process.Kill();
                    }
            }   
        }
        public static void killWinWord()
        {
            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("WINWORD");
            foreach (System.Diagnostics.Process process in processes)
            {
                bool b = process.MainWindowTitle == "";
                if (process.MainWindowTitle == "")
                {
                    process.Kill();
                }
            }
        }

    }
}
    

































////                          总克数    总价      元/g
//   //            百草味      2556 g   229.3     0.0897  
////             三只松鼠      2676g   246.4      0.092  
//  //             良品铺子    2632g   244.3      0.09281
//  //          六种坚果 一个两袋的话     百草味算是便宜的   便宜十块钱                                              
//  //                                             单价            单价         
//          //    榛子        180*2          27.9                                        185*2   33.9   370           180*2     39.8      360 
//          //    夏威夷果    200*3          46.9                                        265*2   46.9   530           280*2     42.9      560
//          //    碧根果      218*2          30.9                                        210*2   38.9   420           190*2     35.9      380
//          //    巴旦木      180*2          28.9                                        235*2   36.9   470           238*2     36.9      476
//          //    松子        200*2          42.9                                        218*2   44.9   436           218*2     45.9      436
//          //    开心果      200*2          51.8                                        225*2   54.9   450           210*2     42.9      420 
   
          

